#include "ThreadPool.h"
#include "Task.h"
#include <iostream>

using std::cout;
using std::endl;

ThreadPool::ThreadPool(size_t threadNum,size_t queSize)
:_threadNum(threadNum)
,_queSize(queSize)
,_taskQue(_queSize)
,_isExit(false)
{}

ThreadPool::~ThreadPool(){

}

void ThreadPool::start(){
    for(size_t idx = 0;idx < _threadNum ; ++idx){
        //创建线程并放入vector
        _threads.push_back(thread(&ThreadPool::doTask,this));
    }
}
void ThreadPool::stop(){
    while(!_taskQue.empty())//避免子线程任务未执行完 程序就退出的现象
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    _isExit = true;
    //唤醒所有子线程
    _taskQue.wakeup();

    for(auto &th : _threads){
        th.join();
    }
}

void ThreadPool::addTask(Task* ptask){
    if(ptask){
        _taskQue.push(ptask);
    }

}

Task * ThreadPool::getTask(){
    return _taskQue.pop();
}

void ThreadPool::doTask(){
    while(!_isExit){ //_isExit == false
        Task *ptask = getTask();
        if(ptask){
            ptask->process();
        }else{
            cout << "ptask == nullptr" << endl;
        }
    }
}
